import type { PropertyPath } from 'lodash';
import { concat, get, isString, map, transform } from 'lodash-es';
import * as XLSX from 'xlsx';

type DataIndex = PropertyPath;
interface Column {
  title: string;
  dataIndex: DataIndex;
}
type BaseValue = string | number;
type Data = Record<any, any>;
type DataSet = BaseValue[][];

export function getDateSet(data: Data[], columns: Column[]): DataSet {
  const titles = map(columns, 'title');
  const valueses = transform(
    data,
    (result, row) => {
      const values = columns.map((column) => {
        const { dataIndex } = column;
        return get(row, dataIndex);
      });
      return result.push(values);
    },
    [] as DataSet,
  );
  const dataSet = concat([titles], valueses);
  return dataSet;
}

export function json2xlsx_export(
  dataSet: DataSet,
  filename = `${Date.now()}.csv`,
) {
  var wb = XLSX.utils.book_new();
  var ws = XLSX.utils.aoa_to_sheet(dataSet);
  XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');
  XLSX.writeFile(wb, filename);
}
